import socket
import struct

ip = '10.11.146.167'
port = 9999
if __name__ == '__main__':
    socket_server = socket.socket()
    socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    socket_server.bind((ip, port))
    socket_server.listen(10)
    conn, addr = socket_server.accept()
    while True:
        recv_data = conn.recv(128)
        # 获取字符串的总长度
        s = struct.unpack('I', recv_data[4:8])
        b1, b2 = recv_data.split(b',')
        byProtocol,all_len,name,message = struct.unpack(f'cI{s[0]-len(b2)}s{len(b2)}s', recv_data)
        if byProtocol == b'T':
            byProtocol = "TCP"
        else:
            byProtocol = "UDP"
        print(f"采用协议{byProtocol},传输数据总长度{all_len},姓名:{name.decode('utf-8').split(',')[0]},说:{message.decode('utf-8')}")
        # byProtocol TCP
        # 姓名
        name = input("请输入你的姓名")
        name = name + ','
        name = name.encode("utf-8")
        # 内容
        message = input("请输入内容")
        message = message.encode("utf-8")
        # 长度
        all_len = len(name) + len(message)
        values = (b'T', all_len, name, message)
        s = struct.Struct(f'cI{len(name)}s{len(message)}s')
        packed_data = s.pack(*values)
        conn.send(packed_data)
    # 关闭服务端和客户端的套接字,表示和客户端停止通信
    new_client.close()
    # 7.关闭服务端套接字,表示不再等待接收客户端的连接请求
    socket_server.close()
